package com.yylending.las.webview;

import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.network.NetworkHelper;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yylending.las.Global;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Url;
import rx.Observable;

/**
 * Created by HenryZhang on 2016/11/2.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class WebViewModel extends Model {
	public final static String TAG = "WebViewModel";

	public final static String POST = "POST";
	public final static String GET = "GET";

	@Override
	public Observable getObservable(Object params, int functionalCode) {
		Service service = (Service) NetworkHelper.createService(Service.class);
		LoadUrl loadUrl = (LoadUrl) params;
		loadUrl.url = Global.BASE_URL + loadUrl.url.replaceFirst("/", "");

		MediaType JSON = MediaType.parse("application/json; charset=utf-8");
		RequestBody mBody = RequestBody.create(JSON, loadUrl.body);
		CLog.i(TAG, "加载链接=" + loadUrl.url);
		if (POST.equalsIgnoreCase(loadUrl.method)) {
			return service.post(loadUrl.url, Global.LOGIN_TOKEN, mBody);
		} else if (GET.equalsIgnoreCase(loadUrl.method)) {
			return service.get(loadUrl.url, Global.LOGIN_TOKEN, mBody);
		}
		return null;

	}

	@Override
	public void onNext(Object obj) {
		CLog.i(TAG, "onNext: " + obj.toString());
		LoadUrlResult result = cast(obj);
		EventAgent.post(result);
	}

	private interface Service {
		@retrofit2.http.GET
		Observable<LoadUrlResult> get(@Url String url, @Header("token") String token, @Body RequestBody body);

		@retrofit2.http.POST
		Observable<LoadUrlResult> post(@Url String url, @Header("token") String token, @Body RequestBody body);
	}

	static class LoadUrlResult extends BaseResultEntity<String> {
	}

	public static class LoadUrl {
		public String method;
		public String url;
		public String body;

		public LoadUrl(String method, String url, String body) {
			this.method = method;
			this.url = url;
			this.body = body;
		}
	}
}
